package com.grass.cropTradingCenter.utils;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class CollectionUtils {
    /**
     * 按照比较规则，将两个列表合并排序
     * 两个列表原本必须是排序好的
     *
     * @param var1
     * @param var2
     * @param comparator
     * @param <T>
     * @return
     */
    public static <T> List<T> mergeSort(List<T> var1, List<T> var2, Comparator<T> comparator, boolean reverse) {
        List<T> list = new ArrayList<>(var1.size() + var2.size());
        int i = 0, j = 0;
        while (i < var1.size() && j < var2.size()) {
            T t1 = var1.get(i);
            T t2 = var2.get(j);
            int compare = comparator.compare(t1, t2);
            if (!reverse) {
                if (compare <= 0) {
                    list.add(t1);
                    i++;
                } else {
                    list.add(t2);
                    j++;
                }
            } else {
                if (compare <= 0) {
                    list.add(t2);
                    j++;
                } else {
                    list.add(t1);
                    i++;
                }
            }
        }
        if (i < var1.size()) {
            list.addAll(var1.subList(i, var1.size()));
        }
        if (j < var2.size()) {
            list.addAll(var2.subList(j, var2.size()));
        }
        return list;
    }

    @AllArgsConstructor
    @Data
    public static class Stu {
        private int id;
        private int age;
    }

    public static void main(String[] args) {
        List<Stu> list1 = new ArrayList<>();
        list1.add(new Stu(5, 0));
        list1.add(new Stu(3, 0));
        list1.add(new Stu(1, 0));

        List<Stu> list2 = new ArrayList<>();
        list2.add(new Stu(0, 6));
        list2.add(new Stu(0, 4));
        list2.add(new Stu(0, 2));
        list2.add(new Stu(0, 0));

        Comparator<Stu> comparator = new Comparator<Stu>() {
            @Override
            public int compare(Stu o1, Stu o2) {
                if (o1.getId() >= o2.getAge()) {
                    return 1;
                } else {
                    return -1;
                }
            }
        };
        ;
        List<Stu> all = mergeSort(list1, list2, comparator, true);
        int x = 1;
    }

    /**
     * 取出列表中指定页码的数据
     *
     * @param sorted
     * @param pageIndex
     * @param pageSize
     * @param <T>
     * @return
     */
    public static <T> List<T> page(List<T> sorted, int pageIndex, int pageSize) {
        final int total = sorted.size();
        final int start = (pageIndex - 1) * pageSize;
        if (start >= total) {
            return Collections.emptyList();
        }
        final int end = Math.min(start + pageSize, total);
        return sorted.subList(start, end);
    }
}
